import Svg from "@/components/base/Svg"
import InputText from "@/components/form_item/InputLazadaCode"
import styled from "@emotion/styled"
import { useAtom, useSetAtom } from "jotai"
import { useEffect, useMemo, useState } from "react"
import { FormProvider, useForm } from "react-hook-form"
import { toast } from "react-toastify"
import InputMoneyText from "@/components/form_item/InputMoneyText"
import { amountAtom, selectedAmountAtom, selectedPaymentMethodAtom } from "../atom"

const AmountContainer = styled.div`
    border-radius: 10rem;
    background-color: #ffffff;
    padding: 12rem;
    margin: 12rem;
`
const AmountTitle = styled.div`
    font-family: "Gilroy";
    font-weight: 500;
    font-size: 16rem;
    letter-spacing: 0%;
    vertical-align: middle;
    text-transform: capitalize;
    margin-bottom: 12rem;
    height: 24rem;
    line-height: 24rem;
`

const MoneyNumList = styled.div`
    display: flex;
    overflow-x: auto;
    gap: 8rem;
    white-space: nowrap;
    padding-bottom: 8rem;
    padding-top: 16rem;
    &::-webkit-scrollbar {
        height: 6rem;
        background: transparent;
        opacity: 0; /* 默认隐藏 */
    }
`
interface isActive {
    isActive: boolean
}
const MoneyBlock = styled.div<isActive>`
    flex: 0 0 auto;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 78rem;
    height: 40rem;
    line-height: 40rem;
    text-align: center;
    border-radius: 6rem;
    background: ${(props) => (props.isActive ? "#ffffff" : "#f2f3f5")};
    color: ${(props) => (props.isActive ? "#054BF0" : "#40444f")};
    border: ${(props) => (props.isActive ? "1rem solid#054BF0" : "none")};
    cursor: pointer;
    font-family: "Gilroy";
    font-weight: 400;
    font-size: 16rem;
`

type DepositAmountProps = {
    min?: number
    max?: number
}

export default function DepositAmount({ min = 100, max = 500000 }: DepositAmountProps) {
    const [selectedPaymentMethod] = useAtom(selectedPaymentMethodAtom)
    const setAtAmount = useSetAtom(amountAtom) //输入框金额
    const methods = useForm({
        defaultValues: {
            amount: "",
        },
        mode: "onChange", // 添加表单模式
    })
    const { setValue: setAmount, reset } = methods
    const amount = methods.watch("amount")

    useEffect(() => {
        setAtAmount(amount || "")
    }, [amount, setAtAmount])

    const MoneyList = useMemo(() => [100, 500, 1000, 2000, 5000, 10000], [])
    const [selectedAmount, setSelectedAmount] = useAtom(selectedAmountAtom)
    const [activeIndex, setActiveIndex] = useState<number>()

    // 监听 amount 变化，清空 selectedAmount 和 activeIndex
    useEffect(() => {
        if (!amount || (selectedAmount && amount !== `${selectedAmount}`)) {
            setSelectedAmount(null) // 清空 selectedAmount
            setActiveIndex(undefined) // 清空 activeIndex
        }
    }, [amount, selectedAmount, setSelectedAmount])
    useEffect(() => {
        if (selectedPaymentMethod === "Lazada") {
            setSelectedAmount(null)
            // 使用 reset 完全重置表单状态
            reset(
                {
                    amount: "",
                },
                {
                    keepErrors: false,
                    keepDirty: false,
                    keepTouched: false,
                    keepIsValid: false,
                    keepDefaultValues: false,
                },
            )
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [selectedPaymentMethod, reset])
    useEffect(() => {
        if (!selectedAmount) {
            setActiveIndex(undefined)
        } else {
            const amountNum = selectedAmount
            if (!isNaN(amountNum)) {
                const index = MoneyList.indexOf(amountNum)
                if (index !== -1) {
                    setActiveIndex(index)
                } else {
                    setActiveIndex(undefined)
                }
            }
        }
    }, [selectedAmount, MoneyList, setAmount])

    const handleClickAmount = (index: number) => {
        setActiveIndex(index)
        setSelectedAmount(MoneyList[index])
        setAmount("amount", MoneyList[index].toString(), { shouldValidate: true })
        methods.trigger("amount")
        toast.success(`The deposit amount has been set to ${MoneyList[index].toLocaleString()}`, {
            position: "top-right",
            autoClose: 1500,
            hideProgressBar: true,
            closeOnClick: true,
            pauseOnHover: false,
            draggable: false,
            progress: undefined,
            theme: "light",
            style: {
                background: "rgba(0, 154, 41, 1)",
                color: "#ffffff",
                boxShadow: "0 2px 12px rgba(0, 154, 41, 0.2)",
                borderRadius: "8rem",
                fontSize: "16rem",
            },
        })
    }

    const formatNumber = (n: number) => n.toLocaleString()
    //动态处理
    const placeholder =
        min && max ? `Enter Amount: ${formatNumber(min)} - ${formatNumber(max)}` : "Enter Amount"

    const renderNormalDeposit = () => (
        <AmountContainer>
            <AmountTitle>Deposit Amount</AmountTitle>
            <FormProvider {...methods}>
                <InputMoneyText
                    fieldName={"amount"}
                    placeholder={placeholder}
                    iconSrc={<Svg src="pages/UserCenterPage/deposit/peso.svg" />}
                    min={min}
                    max={max}
                />
                <MoneyNumList>
                    {MoneyList.map((moneyItem, index) => (
                        <MoneyBlock
                            isActive={activeIndex == index}
                            onClick={() => handleClickAmount(index)}
                            key={index}
                        >
                            {moneyItem.toLocaleString()}
                        </MoneyBlock>
                    ))}
                </MoneyNumList>
            </FormProvider>
        </AmountContainer>
    )

    const renderLazadaDeposit = () => (
        <AmountContainer>
            <AmountTitle>Lazada Voucher Code</AmountTitle>
            <FormProvider {...methods}>
                <form>
                    <InputText
                        fieldName={"amount"}
                        placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
                    />
                </form>
            </FormProvider>
        </AmountContainer>
    )
    return <>{selectedPaymentMethod !== "Lazada" ? renderNormalDeposit() : renderLazadaDeposit()}</>
}
